//引入vue和vuex
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
// import { addLogin } from "@/api/user.js";

const store = new Vuex.Store({
  //全局变量定义
  state: {
    userInfo: uni.getStorageSync("userInfo")
      ? uni.getStorageSync("userInfo")
      : "",
    token: uni.getStorageSync("token") ? uni.getStorageSync("token") : "",
   
  },
  mutations: {
    SET_USERINFO(state, data) {
      state.userInfo = data;
      uni.setStorageSync("userInfo", state.userInfo);
    },
    SET_TOKEN(state, data) {
      state.token = data;
      uni.setStorageSync("token", state.token);
    },
    
  },
  actions: {
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        commit("SET_TOKEN", "");
        let params;
        if (userInfo) {
          params = userInfo;
        } else {
          params = {
            username: uni.getStorageSync("account"),
            password: uni.getStorageSync("password"),
          };
        }
        addLogin(params)
          .then((response) => {
            const { t } = response;
            if (t.user.user.userType == 0) {
              reject("admin");
            } else {
              commit("SET_TOKEN", t.token);
              commit("SET_USERINFO", t.user.user);
              resolve();
            }

            // commit("setAccount", userInfo.username)
            // commit("setPassword", userInfo.password)
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    signOut({ commit }) {
      commit("SET_TOKEN", "");
      commit("SET_USERINFO", "");
    },
  },
});
export default store;
